# pip install flask flask_cors sympy
from typing import Any
from flask import Flask, request, jsonify , Response
from flask_cors import CORS, cross_origin

import json
from sympy import Symbol
from sympy import * # type: ignore

import sys
sys.path.append('./src')
from pao_python import *

app = Flask(__name__)

def symbol_to_str(symbol):
	'''将Symbol对象转换为字符串'''
	if isinstance(symbol, Symbol):
		return str(symbol)
	if isinstance(symbol, dict):
		return {symbol_to_str(k): v for k, v in symbol.items()}
	return symbol

def default_serializer(obj):
		if isinstance(obj, Symbol):
			return {"__type__": "Symbol", "name": obj.name}
		if isinstance(obj, dict):
			return {[symbol_to_str(k), default_serializer(v)] for k, v in obj.items()}
		return obj

def to_response(data):
	'''将数据转换为JSON响应'''
	json_str = json.dumps(data, default=default_serializer, indent=2)
	response =Response(
		response=json_str,
		status=200,
		mimetype='application/json'
	)
	return response

@app.route('/api/math/solveEquation', methods=['POST'])
def req_solve_equations():
	data: Any = request.json
	equations: str = data['equations']
	vars: str = data['variables']
	try:
		solution, exps, vars = solve_equations(equations, vars)
		print(f'求解方程组：{equations}，变量：{vars}，结果：{solution}')

		# 将solution转换为Latex格式的字符串
		latex_solution = parse_expression(solution)
	except Exception as e:
		# 捕获所有异常，确保返回的响应包含CORS头
		return jsonify({"status": "error", "message": str(e)}), 400
	return to_response({"result": symbol_to_str(latex_solution), "equations": [parse_expression(exp) for exp in exps], "variables": vars})

if __name__ == '__main__':
  # 支持跨域访问
	CORS(app)
	app.run(port=5000, debug=True, use_reloader=False)